# view/platform_tabs.py
import tkinter as tk  # 在文件顶部添加
import customtkinter as ctk
import tkinter.ttk as ttk
from config.platforms import PLATFORM_CATEGORIES, COLLECTION_TYPES
from utils.ui_helpers import (
    create_scrollable_checkboxes,
    parse_keywords,
    safe_int,
    safe_float,
    parse_exclude_brands
)
from utils.exporter import export_to_csv
from view.crawler_manager import start_mock_crawling
from data.data_store import DataStore

COLUMNS = ("店铺", "标题", "链接", "价格", "好评率", "关键词", "类目", "销量")
COL_WIDTHS = {
    "店铺": 100, "标题": 200, "链接": 250, "价格": 60,
    "好评率": 70, "关键词": 100, "类目": 120, "销量": 70
}


def build_platform_tab(parent, platform: str, main_gui_ref: ctk.CTk, data_store: DataStore):
    """
    构建指定电商平台的主标签页内容。

    根据平台是否属于“高级支持平台”（如淘宝、京东等），决定使用复杂 Tab 布局还是简单表单布局。

    :param parent: 父容器（通常是主 TabView 中某个平台对应的 tab 页面）
    :param platform: 平台名称，如 "淘宝"、"小红书" 等
    :param main_gui_ref: 主 GUI 窗口引用，用于回调或状态更新
    :param data_store: 全局数据存储对象，用于共享状态和采集结果
    :return: 包含平台 UI 内容的 CTkFrame 实例
    """
    # 创建透明背景的内容框架，作为当前平台 Tab 的根容器
    content_frame = ctk.CTkFrame(parent, fg_color="transparent")
    # 定义支持多采集类型的“高级平台”集合
    advanced_platforms = {"淘宝", "京东", "拼多多", "1688", "抖音", "快手"}

    if platform in advanced_platforms:
        # === 高级平台：使用嵌套 TabView 支持多种采集类型（如关键词采集、商品采集等）===

        # 创建子 TabView，用于切换不同采集类型
        sub_tabview = ctk.CTkTabview(
            content_frame,
            fg_color="#fdfdfd",  # 背景色
            segmented_button_fg_color="#fdfdfd",  # 未选中标签背景色
            segmented_button_selected_color="#3a7ebf",  # 选中标签背景色（蓝色主题）
            segmented_button_selected_hover_color="#2a69b0"  # 选中标签悬停色
        )
        # 使子 TabView 填满 content_frame，并设置内边距
        sub_tabview.pack(fill="both", expand=True, padx=10, pady=(0, 10))

        # 为每种采集类型（如“关键词采集”、“商品采集”）创建一个子标签页
        for ctype in COLLECTION_TYPES:
            sub_tabview.add(ctype)  # 添加子标签页
            # 构建该采集类型的具体 UI（如分类选择、参数输入、启动按钮等）
            _build_collection_tab(sub_tabview.tab(ctype), platform, ctype, main_gui_ref, data_store)

        # 默认激活第一个采集类型（如“关键词采集”）
        sub_tabview.set(COLLECTION_TYPES[0])

    else:
        # === 普通平台：仅提供简化表单（例如只支持单一采集模式）===
        _build_simple_form(content_frame, platform, main_gui_ref, data_store)

    # 将构建好的内容框架返回，供父级布局管理
    return content_frame


def _build_collection_tab(parent, platform: str, ctype: str, main_gui_ref, data_store: DataStore):
    """
    构建单个平台下某种采集类型（如“关键词采集”）的完整 UI 标签页。
    """

    # === 主容器：使用 grid 布局（关键！）===
    main_frame = ctk.CTkFrame(parent, fg_color="transparent")
    main_frame.grid(row=0, column=0, sticky="nsew", padx=10, pady=10)
    parent.grid_rowconfigure(0, weight=1)
    parent.grid_columnconfigure(0, weight=1)

    # 设置主框架网格权重
    main_frame.grid_rowconfigure(0, weight=1)   # 上半部分：参数区
    main_frame.grid_rowconfigure(1, weight=2)  # 下半部分：表格区 ← 占大部分空间
    main_frame.grid_columnconfigure(0, weight=1)

    # === 上半部分：参数输入区域（左右布局）===
    top_frame = ctk.CTkFrame(main_frame, fg_color="transparent")
    top_frame.grid(row=0, column=0, sticky="nsew", padx=10, pady=(0, 10))
    top_frame.grid_columnconfigure(0, weight=1)
    top_frame.grid_columnconfigure(1, weight=1)

    # ========== 左侧：类目多选区域 ==========
    left_frame = ctk.CTkFrame(top_frame, fg_color="#f5f5f5", corner_radius=6)
    left_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 5), pady=5)
    ctk.CTkLabel(left_frame, text="选择类目（多选）：", text_color="#2d2d2d",
                 font=("Microsoft YaHei", 12, "bold")).pack(anchor="w", padx=10, pady=(8, 5))

    categories = PLATFORM_CATEGORIES.get(platform, ["通用类目"])
    key = (platform, ctype)
    create_scrollable_checkboxes(left_frame, categories, data_store.category_vars, key, main_gui_ref)

    # ========== 右侧：采集参数输入区域 ==========
    right_input_frame = ctk.CTkFrame(top_frame, fg_color="transparent")
    right_input_frame.grid(row=0, column=1, sticky="nsew", padx=(5, 0))

    ctk.CTkLabel(right_input_frame, text=f"请输入{ctype}所需信息：", text_color="#2d2d2d") \
        .pack(anchor="w", padx=15, pady=(10, 5))

    widgets = {}

    if ctype == "关键词采集":
        entry = ctk.CTkTextbox(right_input_frame, width=400, height=60, wrap="word",
                               border_width=2, border_color="#999999")
        entry.pack(anchor="w", padx=15, pady=5)

        sales_frame = ctk.CTkFrame(right_input_frame, fg_color="transparent")
        sales_frame.pack(anchor="w", padx=15, pady=5)
        ctk.CTkLabel(sales_frame, text="销量区间（最小 - 最大）：", text_color="#2d2d2d").pack(side="left", padx=(0, 10))
        min_sales_entry = ctk.CTkEntry(sales_frame, placeholder_text="最小销量", width=60)
        max_sales_entry = ctk.CTkEntry(sales_frame, placeholder_text="最大销量", width=60)
        min_sales_entry.pack(side="left", padx=(0, 5))
        ctk.CTkLabel(sales_frame, text="-", text_color="#2d2d2d").pack(side="left", padx=(5, 5))
        max_sales_entry.pack(side="left")

        price_frame = ctk.CTkFrame(right_input_frame, fg_color="transparent")
        price_frame.pack(anchor="w", padx=15, pady=5)
        ctk.CTkLabel(price_frame, text="价格区间（¥最小 - ¥最大）：", text_color="#2d2d2d").pack(side="left", padx=(0, 10))
        min_price_entry = ctk.CTkEntry(price_frame, placeholder_text="最低价", width=60)
        max_price_entry = ctk.CTkEntry(price_frame, placeholder_text="最高价", width=60)
        min_price_entry.pack(side="left", padx=(0, 5))
        ctk.CTkLabel(price_frame, text="-", text_color="#2d2d2d").pack(side="left", padx=(5, 5))
        max_price_entry.pack(side="left")

        brand_frame = ctk.CTkFrame(right_input_frame, fg_color="transparent")
        brand_frame.pack(anchor="w", padx=15, pady=5)
        ctk.CTkLabel(brand_frame, text="排除品牌（多个用逗号分隔）：", text_color="#2d2d2d").pack(side="left", padx=(0, 10))
        brand_exclude_entry = ctk.CTkEntry(brand_frame, placeholder_text="如：苹果, 华为, 小米", width=250)
        brand_exclude_entry.pack(side="left")

        widgets.update({
            "entry": entry,
            "min_sales": min_sales_entry,
            "max_sales": max_sales_entry,
            "min_price": min_price_entry,
            "max_price": max_price_entry,
            "exclude_brand": brand_exclude_entry
        })
    else:
        entry = ctk.CTkEntry(right_input_frame, placeholder_text=f"例如：{platform}{ctype}关键词或链接", width=400)
        entry.pack(anchor="w", padx=15, pady=5)
        widgets["entry"] = entry

    # === 去重选项 ===
    dedup_var = ctk.BooleanVar(value=False)
    data_store.dedup_settings[(platform, ctype)] = dedup_var
    dedup_frame = ctk.CTkFrame(right_input_frame, fg_color="transparent")
    dedup_frame.pack(anchor="w", padx=15, pady=(5, 5))
    ctk.CTkCheckBox(dedup_frame, text="是否链接去重复", variable=dedup_var,
                    font=("Microsoft YaHei", 12), checkbox_width=18, checkbox_height=18).pack(side="left")

    # === 采集页数 ===
    page_frame = ctk.CTkFrame(right_input_frame, fg_color="transparent")
    page_frame.pack(anchor="w", padx=15, pady=(5, 10))
    ctk.CTkLabel(page_frame, text="采集页数：", text_color="#2d2d2d").pack(side="left")
    page_spinbox = ctk.CTkOptionMenu(page_frame, values=["1", "2", "5", "10", "15", "20", "30", "全部"])
    page_spinbox.set("5")
    page_spinbox.pack(side="left", padx=(10, 0))

    # === 下半部分：数据表格 + 控制按钮 ===
    bottom_frame = ctk.CTkFrame(main_frame, fg_color="transparent")
    bottom_frame.grid(row=1, column=0, sticky="nsew", padx=10, pady=(0, 10))
    bottom_frame.grid_rowconfigure(0, weight=0)  # 按钮行：固定高度
    bottom_frame.grid_rowconfigure(1, weight=1)  # 表格：自动拉伸 ← 关键
    bottom_frame.grid_columnconfigure(0, weight=1)

    # 状态提示标签 + 按钮行
    status_and_button_frame = ctk.CTkFrame(bottom_frame, fg_color="transparent")
    status_and_button_frame.grid(row=0, column=0, sticky="ew", padx=20, pady=(0, 12))
    status_and_button_frame.grid_columnconfigure(0, weight=1)

    status_label = ctk.CTkLabel(status_and_button_frame, text="状态：就绪", text_color="green")
    status_label.grid(row=0, column=0, sticky="w")

    button_frame = ctk.CTkFrame(status_and_button_frame, fg_color="transparent")
    button_frame.grid(row=0, column=1, sticky="e")

    def on_start():
        if ctype == "关键词采集":
            kw_text = widgets["entry"].get("1.0", "end").strip()
            keywords = parse_keywords(kw_text)
            min_sales = safe_int(widgets["min_sales"].get())
            max_sales = safe_int(widgets["max_sales"].get())
            min_price = safe_float(widgets["min_price"].get())
            max_price = safe_float(widgets["max_price"].get())
            exclude_brands = parse_exclude_brands(widgets["exclude_brand"].get())
        else:
            keywords = [widgets["entry"].get().strip() or f"{platform}{ctype}"]
            min_sales = max_sales = min_price = max_price = None
            exclude_brands = set()

        selected_categories = [
            cat for cat, var in data_store.category_vars.get((platform, ctype), {}).items()
            if var.get()
        ]

        params = {
            "enable_dedup": data_store.dedup_settings[(platform, ctype)].get(),
            "keywords": keywords,
            "min_sales": min_sales,
            "max_sales": max_sales,
            "min_price": min_price,
            "max_price": max_price,
            "exclude_brands": exclude_brands,
            "selected_categories": selected_categories
        }

        def status_update(text, color):
            status_label.configure(text=text, text_color=color)

        def after_update(delay=0, func=None):
            if func:
                main_gui_ref.after(delay, func)
            else:
                refresh_tree()
                tree.yview_moveto(1.0)

        def finish():
            status_update("状态：完成", "green")

        start_mock_crawling(
            platform=platform,
            ctype=ctype,
            params=params,
            data_store=data_store,
            update_callback=after_update,
            status_callback=status_update,
            finish_callback=finish
        )

    def on_export():
        items = data_store.get_items(platform, ctype)
        filename = f"{platform}_{ctype}_items.csv"
        if export_to_csv(items, filename, COLUMNS):
            status_label.configure(text=f"已导出至 {filename}", text_color="purple")

    ctk.CTkButton(
        button_frame,
        text=f"开始{ctype}",
        command=on_start,
        width=90,
        height=28,
        font=("Microsoft YaHei", 11)
    ).pack(side="left", padx=(0, 8))

    ctk.CTkButton(
        button_frame,
        text="导出",
        command=on_export,
        width=70,
        height=28,
        font=("Microsoft YaHei", 11),
        fg_color="#5a9bd5",
        hover_color="#4a8ac4"
    ).pack(side="left")

    # === 表格容器：使用原生 tk.Frame 并显式拉伸 ===
    tree_frame = tk.Frame(bottom_frame)  # ← 必须是 tk.Frame
    tree_frame.grid(row=1, column=0, sticky="nsew", padx=20, pady=(8, 12))  # sticky="nsew" 是关键！

    # 设置 tree_frame 内部权重
    tree_frame.grid_rowconfigure(0, weight=1)
    tree_frame.grid_columnconfigure(0, weight=1)

    # 创建 Treeview
    tree = ttk.Treeview(tree_frame, columns=COLUMNS, show="headings")
    for col in COLUMNS:
        tree.heading(col, text=col)
        tree.column(col, width=COL_WIDTHS.get(col, 100), anchor="center")

    v_scroll = ttk.Scrollbar(tree_frame, orient="vertical", command=tree.yview)
    h_scroll = ttk.Scrollbar(tree_frame, orient="horizontal", command=tree.xview)
    tree.configure(yscrollcommand=v_scroll.set, xscrollcommand=h_scroll.set)

    tree.grid(row=0, column=0, sticky="nsew")  # ← 必须设置 sticky
    v_scroll.grid(row=0, column=1, sticky="ns")
    h_scroll.grid(row=1, column=0, sticky="ew")

    data_store.set_tree((platform, ctype), tree)

    def refresh_tree():
        tree = data_store.get_tree((platform, ctype))
        for item in tree.get_children():
            tree.delete(item)
        for item_data in data_store.get_items(platform, ctype):
            vals = tuple(item_data.get(col.lower(), "") for col in
                         ["shop", "title", "link", "price", "rating", "keyword", "category", "sales"])
            tree.insert("", "end", values=vals)

    refresh_tree()


def _build_simple_form(parent, platform: str, main_gui_ref, data_store: DataStore):
    """简化版表单（普通平台）"""
    main_frame = ctk.CTkFrame(parent, fg_color="transparent")
    main_frame.pack(fill="both", expand=True, padx=10, pady=10)
    ctk.CTkLabel(main_frame, text=f"{platform} 简易采集（待实现）", font=("Microsoft YaHei", 12)).pack(pady=20)